import axios from 'axios';
import React, { useState, useEffect, useRef } from 'react';
import { LeftOutline } from 'antd-mobile-icons'
import { useNavigate, useParams } from 'react-router-dom'
import  './Chat.css'

function Chat() {
  const [message, setMessage] = useState('');
  const [serverMessage, setServerMessage] = useState('');
  const [chat, setChat] = useState([])
  const fileReaderRef = useRef(null);
  const wsRef = useRef(null);
  const { name } = useParams()

  useEffect(() => {

    getChat()

    wsRef.current = new WebSocket('ws://127.0.0.1:5000');

    wsRef.current.onopen = () => {
      console.log('WebSocket connection opened');
    };

    wsRef.current.onmessage = (event) => {
      if (event.data instanceof Blob) {
        if (!fileReaderRef.current) {
          fileReaderRef.current = new FileReader();
        }

        fileReaderRef.current.onloadend = () => {
          const result = fileReaderRef.current.result;
          if (typeof result === 'string') {
            console.log('Received message from WebSocket as text:', result);
            let res = eval("(" + result + ")")

            res.name = "张三"

            axios.post('http://127.0.0.1:3000/chat', res)

            setServerMessage(res.msg);
            console.log(serverMessage)
          } else {
            console.warn('Failed to read Blob as text:', result);
            setServerMessage('Failed to read Blob as text');
          }
        };

        fileReaderRef.current.readAsText(event.data);
      } else if (typeof event.data === 'string') {
        console.log('Received message from WebSocket as string:', event.data);
        setServerMessage(event.data);
      } else {
        console.warn('Received non-string, non-Blob data:', event.data);
        setServerMessage('Received unsupported data type');
      }
    };

    wsRef.current.onclose = () => {
      console.log('WebSocket connection closed');
    };

    wsRef.current.onerror = (error) => {
      console.error('WebSocket error:', error);
      setServerMessage('WebSocket error occurred');
    };

    return () => {
      if (wsRef.current) {
        wsRef.current.close();
      }
      if (fileReaderRef.current) {
        fileReaderRef.current.onloadend = null;
        fileReaderRef.current = null;
      }
    };


  }, [chat]);

  const getChat = async () => {

    let { data: { list } } = await axios.get('http://127.0.0.1:3000/chat')

    setChat(list)
  }

  const handleSendMessage = (event) => {
    event.preventDefault();
    if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
      if (message === '') {
        return
      } {
        let data = { "msg": message, "state": 0 }
        wsRef.current.send(JSON.stringify(data));
        setMessage('');
      }
    }
  };
  const [msg] = useState("/img/3.jpg")
  const navv = useNavigate()
  return (
    <div className="App">
      <div className='sever conter' style={{ marginTop: "0.925rem" }}>
        <LeftOutline onClick={() => navv(-1)} /><span style={{ marginLeft: "7.5rem" }}>张三的聊天界面</span>
      </div>
      <div style={{ marginTop: "1.25rem", marginLeft: "0.625rem" }}>
        {chat.map(item => {
          return <div key={item._id} style={{ width: "100%" }}>
            <div className={item.state === '1' ? "chat-left" : "chat-right"}>
              <img src={item.state === '0' ? msg : "/img/0.jpg"} alt="" style={{ width: "1rem", height: "1rem" }} className={item.state === '1' ? "chat-left-img" : "chat-right-img"} />
              <p className={item.state === '1' ? "chat-left-p" : "chat-right-p"}>{item.msg}</p>
            </div>
          </div>
        })}
      </div>
      <div className="chat-bottom-send" style={{ marginBottom: "0.625rem" }}>
        <form onSubmit={handleSendMessage}>
          <input type="text" value={message} onChange={(e) => setMessage(e.target.value)} />
          <button type="submit" style={{ border: "none", marginLeft: "0.625rem" }}>发送</button>
        </form>
      </div>
    </div>
  );
}

export default Chat;